const router = require('koa-router')()
router.prefix('/api/user')

const controller = require('../controller/user')

const { SuccessModul, ErrorModule } = require('../classes/result')
const User = require('../classes/user')

const usernameCheck = require('../middleware/username-check')
const loginCheck = require('../middleware/login-check')

router.post('/login', async (ctx, next) => {
  const { username, password } = ctx.request.body
  const user = new User({ username, password })
  try {
    const result = await controller.userLogin(user)
    ctx.session.user = result
    ctx.body = new SuccessModul(result)
  }
  catch (msg) {
    ctx.body = new ErrorModule(msg)
  }
})

router.post('/register', usernameCheck, async (ctx, next) => {
  const { username, password, state, keyword } = ctx.request.body
  const user = new User({ username, password, state })
  
  const check = user.checkKeyword({ keyword, state })
  if (!check) {
    ctx.body = new ErrorModule('注册码错误')
    return
  } 
  
  try {
    const result = await controller.userRegister(user)
    ctx.session.user = {
      username,
      state,
      id: result.id
    }
    ctx.body = new SuccessModul(result)
  } 
  catch (msg) {
    ctx.body = new ErrorModule(msg)
  }
})

router.post('/nameCheck', usernameCheck, async (ctx, next) => {
  ctx.body = new SuccessModul()

})

router.get('/getUser', loginCheck, async (ctx, next) => {
  ctx.body = new SuccessModul(ctx.session.user)
})

router.get('/logout', loginCheck, async (ctx) => {
  ctx.session.user = null
  ctx.body = new SuccessModul('logout success')
})

module.exports = router